<?php


namespace App\Http\Controllers\Admin\Gift;


use App\Enums\GiftCategoryIdEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
//礼物分类
class CategoryController extends BaseController
{
    /**
     * @api {post} /gift/category 新增礼物分类
     *
     * @apiGroup 礼物-分类
     *
     * @apiParam {String} category_name 分类名称，必须
     * @apiParam {Int} gift_desc_bg_id 礼物说明背景id，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {Int} status 状态：1：启用；0：禁用，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        $param = $request->only('category_name', 'gift_desc_bg_id', 'sort', 'status');
        $v = app('validator')->make($param, [
            'category_name' => 'required|string|max:15',
            'gift_desc_bg_id' => 'required|integer|min:1',
            'sort' => 'required|integer|min:0|max:2100000000',
            'status' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['parent_category_id'] = GiftCategoryIdEnum::GIFT;
        $res = app('repo_gift')->addOrEditCategory($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '添加失败');
    }

    /**
     * @api {put} /gift/category 编辑礼物分类
     *
     * @apiGroup 礼物-分类
     *
     * @apiParam {Int} id 分类id，必须
     * @apiParam {Int} parent_category_id 父分类id，必须
     * @apiParam {String} category_name 分类名称，必须
     * @apiParam {Int} gift_desc_bg_id 礼物说明背景id，必须
     * @apiParam {Int} sort 排序号，必须
     * @apiParam {String} status 状态：1：启用；2：禁用，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'category_name', 'gift_desc_bg_id', 'sort', 'status');
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
            'category_name' => 'required|string|max:15',
            'gift_desc_bg_id' => 'required|integer|min:1',
            'sort' => 'required|integer|min:0|max:2100000000',
            'status' => 'required|integer|in:0,1',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $param['parent_category_id'] = GiftCategoryIdEnum::GIFT;
        $res = app('repo_gift')->addOrEditCategory($param);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '编辑失败');
    }

    /**
     * @api {get} /gift/category/all 获取所有礼物分类
     *
     * @apiGroup 礼物-分类
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
        {
        "id": 1,
        "parent_id": 0,
        "title": "礼物",
        "status": 1,
        "gift_desc_bg_id": 1,
        "sort": 0,
        "gift_desc_bg_url": "http://jfssssls.jpg",
        "children": [
            {
            "id": 4,
            "parent_id": 1,
            "title": "热销",
            "status": 1,
            "gift_desc_bg_id": 1,
            "sort": 0,
            "gift_desc_bg_url": "http://jfssssls.jpg",
            "children": []
            }
        ]
        }
    ]
    }
     */
    public function all()
    {
        $list = app('model_gift_categories')
            ->select('id', 'parent_id', 'title', 'status', 'gift_desc_bg_id', 'sort')
            ->where('parent_id', 0)
            ->where('is_delete', 0)
            ->orderBy('sort', 'asc')->get()->toArray();
        $list = $this->getTree($list);
        return Response::sendData($list);
    }

    //递归查询所有子分类
    private function getTree(&$list)
    {
        foreach ($list as &$row) {
            $row['gift_desc_bg_url'] = app('model_gift_desc_bg')->where('id', $row['gift_desc_bg_id'])->value('img_url');
            $children = app('model_gift_categories')
                ->select('id', 'parent_id', 'title', 'status', 'gift_desc_bg_id', 'sort')
                ->where('parent_id', $row['id'])
                ->where('is_delete', 0)
                ->get()->toArray();
            if ($children) {
                $row['children'] = $children;
                $this->getTree($row['children']);
            }
        }
        return $list;
    }

    /**
     * @api {get} /gift/category/sub-categories 获取礼物子分类
     *
     * @apiGroup 礼物-分类
     *
     * @apiParam {int} category_id 父分类id，默认是‘礼物’的分类id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 4,
    "title": "热销",
    "status": 1,
    "gift_desc_bg_id": 10,
    "gift_desc_img_url": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/d513f4d65cc65e53f435e251f7c0ae2buwLM0.png",
    "sort": 0
    }
    ]
    }
     */
    public function getSubCategories(Request $request)
    {
        $param = $request->only('category_id');
        $v = app('validator')->make($param, [
            'category_id' => 'integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $categoryId = $param['category_id'] ?? GiftCategoryIdEnum::GIFT;

        $subCategories = app('model_gift_categories')->from('ln_gift_categories as gc')
            ->leftJoin('ln_gift_desc_bg as gdb', 'gc.gift_desc_bg_id', '=', 'gdb.id')
            ->select('gc.id', 'gc.title', 'gc.status', 'gc.gift_desc_bg_id', 'gdb.img_url as gift_desc_img_url', 'gc.sort')
            ->where('gc.parent_id', $categoryId)
            ->where('gc.is_delete', 0)
            ->get();
        return Response::sendData($subCategories);
    }

    /**
     * @api {delete} /gift/category 删除礼物分类
     *
     * @apiGroup 礼物-分类
     *
     * @apiParam {Int|String} ids 分类id，多个用英文逗号连接，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[]}
     */
    public function del(Request $request)
    {
        $ids = $request->ids;

        if (empty($ids)) throw new BasicException(0, '请选择要删除的id');

        $ids = explode(',', $ids);

        $res = app('model_gift_categories')->whereIn('id', $ids)->update(['is_delete' => 1]);
        if ($res) {
            return Response::sendData([]);
        }
        throw new BasicException(0, '删除失败');
    }
}